import { Effect, Reducer, Subscription } from 'umi';

import { delay } from '@/utils/index';

export interface IndexModelState {
  name: string;
  count: number;
}

export interface IndexModelType {
  // 如果有一个字符串，而且这个字符串是不会变的，那么我们可以直接将变量类型写成这个字符串
  namespace: 'index';
  state: IndexModelState;
  effects: {
    asyncAdd: Effect;
  };
  reducers: {
    changeName: Reducer;
    add: Reducer;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  // 模块名称
  namespace: 'index',

  // 仓库数据
  state: {
    name: 'zhangsan',
    count: 5,
  },

  // 写异步函数的, 类似于vuex的actions
  effects: {
    *asyncAdd({ payload }, { call, put }) {
      yield delay(2000);

      yield put({
        type: 'add',
      });
    },
  },

  // 同步函数，类似于vuex的mutations
  reducers: {
    changeName(state, action) {
      // console.log('changeName', action);
      return {
        ...state,
        name: action.name,
      };
    },
    add(state, action) {
      return {
        ...state,
        count: state.count + 1,
      };
    },
  },

  // 可以用于做url监听之类的
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default IndexModel;
